﻿using System;
using System.Data;
using System.Drawing;
using System.Web.UI.WebControls;

using HsTec.Mobile.Green.BLL;
using System.Drawing.Imaging;
using HsTec.Mobile.Green.Util;
using Baimasoft.Manage.SqlServerDAL;

public partial class ReportAnalysis_TemperatureAnalysis : System.Web.UI.Page
{
    ReportAnalysisBLL bll = new ReportAnalysisBLL();
    Param MyP = new Param();
    private string sArea = String.Empty;
    private string sCheck = String.Empty;

    protected void Page_Load(object sender, EventArgs e)
    {
        //if ((string)Session["Baimasoft_Pers_ID"] == null)
        //{
        //    Response.Redirect("../Logon.aspx");
        //}
        if (!this.IsPostBack)
        {
            //绑定区域下拉框
            lstArea.Attributes.Add("onclick", "FindSelectedItems(this," + txtArea.ClientID + ");");
            this.BindlstArea();
            //绑定指标选项下拉框
            lstItems.Attributes.Add("onclick", "FindSelectedItems(this," + txtItems.ClientID + ");");
            this.BindlstItems();
            txtMin.Attributes.Add("onblur", "setArea()");
            txtMax.Attributes.Add("onblur", "setArea()");
            try
            {
                Indicator.Text = Request.QueryString["sIndicator"].ToString();
            }
            catch
            {

            }
            GridView1.Attributes.Add("BorderColor", "LightSkyBlue");
            if (ViewState["sortDirection"] == null)
            {
                ViewState["sortDirection"] = " ASC";
            }
            if (ViewState["sortExpression"] == null)
            {
                ViewState["sortExpression"] = String.Empty;
            }
            this.BindtvYears();
        }
    }
    /// <summary>
    /// 绑定时间树
    /// </summary>
    private void BindtvYears()
    {
        ddlYears.DataTextField = "Name";
        ddlYears.DataValueField = "Name";
        ddlYears.DataSource = MyP.GetCodeByParentCode("1");
        ddlYears.DataBind();
        ddlYears.Items.Insert(0, "请选择...");
        ddlYears.Items[0].Value = "";
    }

    /// <summary>
    /// 绑定指标选项
    /// </summary>
    private void BindlstItems()
    {
        lstItems.DataSource = bll.GetItemsList();
        lstItems.DataTextField = "descript";
        lstItems.DataValueField = "colname";
        lstItems.DataBind();
    }

    /// <summary>
    /// 绑定区域数据
    /// </summary>
    private void BindlstArea()
    {
        lstArea.DataSource = bll.GetAreaALL();
        lstArea.DataTextField = "Name";
        lstArea.DataValueField = "ID";
        lstArea.DataBind();
    }

    private void BindGridViewData()
    {
        string sItems = String.Empty;
        for (int i = 0; i < lstItems.Items.Count; i++)
        {
            if (lstItems.Items[i].Selected == true)
            {
                sItems += sItems == String.Empty ? lstItems.Items[i].Value + " AS [" + lstItems.Items[i].Text.Replace("-", "") + "]" : "," + lstItems.Items[i].Value + " AS [" + lstItems.Items[i].Text.Replace("-", "") + "]";
            }
        }
        DataView mydv = bll.GetReportList(GetSearchString(), sItems);
        if (!String.IsNullOrEmpty(ViewState["sortExpression"].ToString()))
            mydv.Sort = ViewState["sortExpression"].ToString() + ViewState["sortDirection"].ToString();
        GridView1.DataSource = mydv;
        GridView1.DataBind();
    }

    private string GetSearchString()
    {
        sArea = String.Empty;
        string searchStr = "(1=1)";
        for (int i = 0; i < lstArea.Items.Count; i++)
        {
            if (lstArea.Items[i].Selected == true)
            {
                sArea += sArea == String.Empty ? lstArea.Items[i].Value : "," + lstArea.Items[i].Value;
            }
        }
        if (!String.IsNullOrEmpty(sArea))
            searchStr += " and Area_ID in (" + sArea + ")";
        else
            searchStr += " and Area_ID in (-1)";
        //获取所选择的年月
        sCheck = ddlYears.SelectedValue;
        if (!String.IsNullOrEmpty(sCheck))
        {
            searchStr += " and Years in (" + sCheck + ") ";
        }
        return searchStr;
    }

    protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
    {

    }
    protected void btnQuery_Click(object sender, EventArgs e)
    {
        if (!String.IsNullOrEmpty(ddlYears.SelectedValue))
        {
            this.BindGridViewData();
            GridView1.Visible = true;
            imgReport.Visible = false;
            cbShowData.Visible = false;
        }
        else
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请选择年月！');</script>");
        }
    }
    protected void btnReport_ServerClick(object sender, EventArgs e)
    {
        if (String.IsNullOrEmpty(ddlYears.SelectedValue))
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请选择年月！');</script>");
            return;
        }
        string sItems = String.Empty;
        for (int i = 0; i < lstItems.Items.Count; i++)
        {
            if (lstItems.Items[i].Selected == true)
            {
                sItems += sItems == String.Empty ? lstItems.Items[i].Value + " AS [" + lstItems.Items[i].Text.Replace("-", "") + "]" : "," + lstItems.Items[i].Value + " AS [" + lstItems.Items[i].Text.Replace("-", "") + "]";
            }
        }
        //输出图表
        BarChart myBc = new BarChart();

        string tmp = String.Empty;
        DataTable dt = bll.GetReportList(GetSearchString(), sItems).Table;
        string imgUrl = Server.MapPath("Graphic\\Graphic") + (string)Session["Baimasoft_Pers_ID"] + ".jpg";
        if (dt.Rows.Count > 0)
        {
            //执行同月图表
            if (sCheck.Split(',').Length > 1)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('生成同月图表，请选择某个月份！');</script>");
                return;
            }
            tmp = dt.Rows[0]["年月"].ToString();
            try
            {
                tmp = tmp.Substring(0, 4) + "年" + tmp.Replace(tmp.Substring(0, 4), "") + "月";
            }
            catch
            {

            }
            myBc.ChartTitle = tmp + "不同地区耗电量图表";
            myBc.ChartXTitle = "地区";
            myBc.ChartYTitle = "电量";
            myBc.TextValue = "地区";
            myBc.DataSource = dt;
            if (brlGraphic.SelectedValue == "1")
            {
                Bitmap img = myBc.DrawBarChart();
                img.Save(imgUrl, ImageFormat.Jpeg);
            }
            else
            {
                if (dt.Rows.Count <= 1)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('生成折线图至少需要两条以上的记录数，请更改查询条件！');</script>");
                    return;
                }
                Bitmap img = myBc.DrawBrokenLine();
                img.Save(imgUrl, ImageFormat.Jpeg);
            }
            GridView1.Visible = false;
            imgReport.Visible = true;
            cbShowData.Visible = true;
            cbShowData.Checked = false;
            Random rnd = new Random();
            imgReport.ImageUrl = "Graphic\\Graphic" + (string)Session["Baimasoft_Pers_ID"] + ".jpg?" + DateTime.Now.Millisecond + "&" + rnd.Next(100).ToString();
        }
        else
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('没有数据用于生成图表，请重新选择范围！');</script>");
        }
    }

    protected void btn_Click(object sender, EventArgs e)
    {
        lstArea.Items.Clear();
        this.BindlstArea();
        txtArea.Value = String.Empty;
    }
    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (ViewState["sortDirection"].ToString() == " ASC")
        {
            ViewState["sortDirection"] = " DESC";
        }
        else
        {
            ViewState["sortDirection"] = " ASC";
        }
        ViewState["sortExpression"] = e.SortExpression;
        this.BindGridViewData();
    }
    protected void cbShowData_CheckedChanged(object sender, EventArgs e)
    {
        if (cbShowData.Checked)
        {
            GridView1.Visible = true;
            this.BindGridViewData();
        }
        else
        {
            GridView1.Visible = false;
        }
    }
    protected void btnArea_Click(object sender, EventArgs e)
    {
        lstArea.DataSource = bll.GetAreaByTemp(txtMin.Text.Trim(),txtMax.Text.Trim(),ddlYears.SelectedValue.Trim());
        lstArea.DataTextField = "Name";
        lstArea.DataValueField = "ID";
        lstArea.DataBind();
    }
}
